package com.abocode.aichat.client;

import com.abocode.aichat.server.stanza.StanzaWrapper;
import com.abocode.aichat.utils.UUIDUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.Map;

public class TcpClientHandler extends SimpleChannelInboundHandler<String> {

    Log log = LogFactory.getLog(TcpClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("channelRead0" + msg);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        log.info("channelRegistered");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        log.info("channelUnregistered");
    }


    public void register(Channel channel) {
        Map map = new HashMap();
        StanzaWrapper.wrapper(UUIDUtils.sn(), "gateway", "auth", map);
        try {
            channel.writeAndFlush("").sync();
        } catch (InterruptedException e) {
            throw new RuntimeException("register fail");
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.info("exceptionCaught:" + cause.getMessage());
    }
}